package greenhouse

import (
	rich_err "app/error"
	"app/models"
	"app/service"
	"app/service/orders"
	"errors"
	"math"
	"strconv"

	"github.com/jinzhu/gorm"

	"github.com/gin-gonic/gin"
)

func Gets(context *gin.Context) ([]*models.GreenhouseDetail, *models.Pager, *rich_err.RichError) {
	base := models.Orm.Model(&models.Greenhouse{}).
		Select("greenhouse.*, goadmin_users.name as manager_name").
		Joins("LEFT JOIN goadmin_users ON greenhouse.manager_id = goadmin_users.id")

	results, pager, err := service.GetDetails[models.GreenhouseDetail](context, base, models.Greenhouse{}.TableName(), map[string]string{"manager_name": "goadmin_users.name"})

	if err != nil {
		return nil, nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	return results, pager, nil
}

func Get(id string) (*models.GreenhouseDetail, *rich_err.RichError) {
	base := models.Orm.Model(&models.Greenhouse{}).
		Select("greenhouse.*, goadmin_users.name as manager_name").
		Joins("LEFT JOIN goadmin_users ON greenhouse.manager_id = goadmin_users.id")

	result, err := service.GetDetail[models.GreenhouseDetail](id, base)

	if err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	return result, nil
}

func Create(context *gin.Context) (*models.GreenhouseDetail, *rich_err.RichError) {
	req := new(models.GreenhouseCore)
	if err := context.ShouldBindJSON(req); err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	// 检查是否存在相同名称的记录
	var existingGreenhouse models.Greenhouse
	if err := models.Orm.Where("name = ?", req.Name).First(&existingGreenhouse).Error; err == nil {
		// 如果找到记录，直接返回
		return Get(strconv.Itoa(existingGreenhouse.ID))
	} else if !errors.Is(err, gorm.ErrRecordNotFound) {
		// 如果查询出错，返回数据库错误
		return nil, rich_err.NewError(rich_err.DatabaseFailed, err)
	}
	data := models.Greenhouse{GreenhouseCore: *req}
	result := models.Orm.Create(&data)
	if result.Error != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}
	return Get(strconv.Itoa(data.ID))
}

func Update(context *gin.Context) (*models.GreenhouseDetail, *rich_err.RichError) {
	req := new(models.GreenhouseDelta)
	if err := context.ShouldBindJSON(req); err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}

	data, err := service.Get[models.Greenhouse](context)
	if err != nil {
		return nil, rich_err.NewError(rich_err.RequestInvalid, err)
	}
	if req.Name != nil {
		data.Name = req.Name.(string)
	}
	if req.Remark != nil {
		data.Remark = req.Remark.(string)
	}

	if req.IsActive != nil {
		data.IsActive = int(math.Round(req.IsActive.(float64)))
	}
	if req.ManagerID != nil {
		data.ManagerID = int(math.Round(req.ManagerID.(float64)))
	}
	result := models.Orm.Save(data)
	if result.Error != nil {
		return nil, rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}
	return Get(strconv.Itoa(data.ID))
}

func Delete(context *gin.Context) *rich_err.RichError {
	data, err := service.Get[models.Greenhouse](context)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil
		}
		return rich_err.NewError(rich_err.RequestInvalid, err)
	}
	result := models.Orm.Delete(data)
	if result.Error != nil {
		return rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}

	// 联动删除其他项
	conditions := map[string]interface{}{"greenhouse_id = ?": data.ID}
	richErr := service.DeleteByConditions[models.GreenhouseAllocationRecord](conditions)
	if richErr != nil {
		return richErr
	}
	richErr = service.DeleteByConditions[models.MedicationRecord](conditions)
	if richErr != nil {
		return richErr
	}

	richErr = service.DeleteByConditions[models.SeedlingRecord](conditions)
	if richErr != nil {
		return richErr
	}

	richErr = service.DeleteByConditions[models.SeedbedAllocationRecord](conditions)
	if richErr != nil {
		return richErr
	}

	richErr = service.DeleteByConditions[models.SeedbedAllocationBatchRecord](conditions)
	if richErr != nil {
		return richErr
	}

	// 由于删除了 SeedlingRecord 出苗记录 和 SeedbedAllocationRecord,SeedbedAllocationBatchRecord 苗床分配记录, 需要更新orders表的 已出苗数量和已分配苗床数量
	var orderIDs []int
	err = models.Orm.Model(&models.Orders{}).Pluck("order_id", &orderIDs).Error
	if err != nil {
		return rich_err.NewError(rich_err.DatabaseFailed, result.Error)
	}

	for _, orderID := range orderIDs {
		err = orders.UpdateDeliveredQuantity(orderID)
		if err != nil {
			return rich_err.NewError(rich_err.DatabaseFailed, err)
		}
		err = orders.UpdateAllocatedSeedbedQuantity(orderID)
		if err != nil {
			return rich_err.NewError(rich_err.DatabaseFailed, err)
		}
	}

	return nil
}
